package com.ynet.middleground.mobile.approve.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.ynet.core.util.IDUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * TraceFilter 日志追踪过滤器
 *
 * @author liulx
 * @date 2023/04/10 16:49
 */
@Component
@Slf4j
public class TraceFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        FilterChain filterChain) throws ServletException, IOException {
        // add traceId
        String traceId = generateTraceId();
        MDC.put("traceId", traceId);
        MDC.put("logId", traceId);
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    private String generateTraceId() {
        return " - " + IDUtil.getSecureRandomId();
    }
}
